import React, { useEffect, useState } from 'react'
import {
  Button,
  DatePicker,
  Form,
  Input,
  message,
  Radio,
  Select,
  Upload
} from 'antd';
import { fetchRequest } from '../../../../../utils/Request';
import { url } from '../../../../../utils/url';
import { useSingleState } from "nice-hooks";
import getImgInfo from '../../../../../utils/getImgInfo';
import { PlusOutlined } from '@ant-design/icons'
import "./QrcodeList.css"
import { useParams } from 'react-router';
import { getSecretString } from '../../../../../utils/encrypt';
import { Store } from 'rc-field-form/lib/interface';
import moment from 'moment'
import { useRequest } from '@umijs/hooks';

interface ValidateState {
  state: "" | "success" | "warning" | "error" | "validating" | undefined,
  help: string | undefined,

}
const uploadButton = (
  <div>
    <PlusOutlined />
    <div style={{ marginTop: 8 }}>上传照片</div>
  </div>
);
function QrcodeList() {

  const { token, value, label } = useParams<any>()
  const labeltext = decodeURI(label)
  const [form] = Form.useForm();
  const { Option } = Select;
  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 14 },
  };
  const tailLayout = {
    wrapperCol: { offset: 5, span: 14 },
  };
  const [state, setState] = useSingleState({ fileStoreName: "" })
  const [validatePhoto, setvalidatePhoto] = useState<ValidateState>({ state: undefined, help: undefined })
  const [userTypeList, setUserTypeList] = useState<any>([{ userTypeId: "1", userTypeName: "干部职工" }, { userTypeId: "2", userTypeName: "借调人员" }, { userTypeId: "3", userTypeName: "院内租住户" }]);
  const userTypeOptions = userTypeList.map((d: any, index: number) => <Option value={d.userTypeId} key={index}>{d.userTypeName}</Option>);
  const [photoInfo, setphotoInfo] = useState({
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: []
  })
  //是否通过Img检测
  const [imgFlag, setImgFlag] = useState(false);

  function normFile({ fileList }: any) {
    // console.log('Upload event:', fileList);
    // // return e.fileList;
    if (fileList.length > 0 && fileList[0].status === "done") {
      if (fileList[0].response.success) {
        setState({ fileStoreName: fileList[0].response.files[0].fileStoreName })
        const myFile = [];
        myFile[0] = {
          ...fileList[0],
          url: url.GET_PERSON_FACE_URL +
            "accessToken=" +
            getImgInfo(fileList[0].response.files[0].fileStoreName)
        }
        return myFile
      } else {
        const myFile = [];
        myFile[0] = {
          ...fileList[0],
          status: "error"
        }
        return myFile;
      }
    } else
      return fileList
  };
  const removePicture = () => {
    setvalidatePhoto({ state: '', help: "" })
    setState({
      fileStoreName: ''
    }, () => {
    })
    setImgFlag(false)
  }
  //当上传的文件变化的时候
  function onFileChange(info: any) {
    // if(info.file.status === "removed"){
    //     setImgFlag(false)
    // }
    if (info.file.status === 'done') {
      const params = {
        storeName: state.fileStoreName
      }
      checkUserPhoto(params);
    }
    setphotoInfo({ ...photoInfo, fileList: info.fileList })
  }

  //人脸检测接口
  async function checkUserPhoto(params: any) {
    try {
      setvalidatePhoto({ state: 'validating', help: "" })
      const json = await fetchRequest(url.CHECK_FACE_URL,
        params, {
        "Accept-type": "application/json",
        "Content-type": "application/json;charset=utf-8",
        token: token
      }
      );
      if (json.success) {
        setvalidatePhoto({ state: "success", help: json.result })
        return Promise.resolve();
      } else {
        setImgFlag(true)
        setvalidatePhoto({ state: "error", help: json.result });
        return Promise.reject(json.result)
      }
    } catch (error: any) {
      setvalidatePhoto({ state: "error", help: "照片验证失败" })
      return Promise.reject("照片验证失败")
    }
  }

  useEffect(() => {

  }, [])
  const onFinish = (values: Store) => {
    if (imgFlag) {
      message.error('人脸识别未通过')
      return
    }


    const data = {
      studentName: values.studentName,
      phone: getSecretString(values.phone),
      credentialsNum: getSecretString(values.credentialsNum),
      studentId: getSecretString('sjyj' + values.phone),
      sex: values.sex,
      photo: state.fileStoreName,
      teacherTypeId: values.teacherTypeId,
      userTypeId: '2',
      userType: '2'
    };
    const params = {
      deptId: value,
      userTypeId: '2',
      listUserDept: [data]
    };
    addNewStaffOne.run(params)
  }
  const addNewStaffOne = useRequest(addNewStaffOneRequest, {
    manual: true,
    loadingDelay: 200
  })

  async function addNewStaffOneRequest(params: any) {
    try {
      const json = await fetchRequest(url.ADD_STUDENT_INFORMATION, params, {
        "Accept-type": "application/json",
        "Content-type": "application/json;charset=utf-8",
        token: token
      });
      if (json.success) {
        message.destroy();
        message.success("新增成功!");
        form.resetFields();
      } else {
        message.destroy();
        message.error("新增失败！" + json.info.errorList[0].errorTitle);

      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  const beforeUpload = (file: any, fileList: any) => {
    // new Compressor(file, {
    //     quality: 0.4,
    //  async success(result:any) {
    //       const formData = new FormData();
    //       formData.append('file', result, result.name);
    //       return formData
    //     },
    //     error(err) {
    //       console.log(err.message);
    //     },
    //   });
  }
  return (
    <div className='qrcodeBox'>
      <Form form={form} {...layout} onFinish={onFinish} initialValues={{ deptId: labeltext }}>
        <Form.Item label="姓名" name="studentName" rules={[{
          required: true, message: '必须要输入用户名'
        },
        {
          max: 20,
          message: '姓名长度过长'
        }
          ,
        {
          pattern: /^[\u4e00-\u9fa5]|[a-zA-Z]$/,
          message: '姓名不符合规范'
        }
        ]}>
          <Input placeholder="请填写姓名" />
        </Form.Item>

        <Form.Item label="性别" name="sex" rules={[{ required: true, message: '必须选择性别' }]}>
          <div>
            <Radio.Group>
              <Radio value={"男"} key={"1"}>男</Radio>
              <Radio value={"女"} key={"2"}>女</Radio>
            </Radio.Group>
          </div>
        </Form.Item>

        <Form.Item label="人员类型" name="teacherTypeId" rules={[{ required: true, message: "必须要选择人员类型!" }]}>
          <Select
            style={{ width: '100%' }}
            placeholder="请选择人员类型"
          // onChange={typeOnChange}
          >
            {userTypeOptions}
          </Select>
        </Form.Item>

        <Form.Item label="联系电话" name="phone" rules={[{ required: true, message: '必须要输入手机号码' }, {
          pattern: /^1[3456789]\d{9}$/,
          message: '手机号码格式错误！'
        }]}>
          <Input placeholder="请输入手机号码" />
        </Form.Item>
        <Form.Item label="身份证号" name="credentialsNum" rules={[{
          required: true,
          message: '必须要输入身份证号码'
        }, {
          pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          message: '身份证格式错误！'
        }]}>
          <Input placeholder="请输入身份证号码" />
        </Form.Item>
        <Form.Item
          validateStatus={validatePhoto.state}
          help={validatePhoto.help}
          hasFeedback
          valuePropName="fileList"
          getValueFromEvent={normFile} label="人脸照片" name="facePic">
          <Upload
            listType="picture-card"
            showUploadList={{
              showPreviewIcon: true,
              showDownloadIcon: true
            }}
            action={url.UPLOAD_PERSON_URL}
            beforeUpload={beforeUpload}
            onChange={onFileChange}
            onRemove={removePicture}
            headers={{ token: token }}
            accept="image/*"
          // capture="camera"
          // accept=".png,.svg,.jpg,.jpeg,.gif"
          >
            {photoInfo.fileList.length >= 1 ? null : uploadButton}
          </Upload>
        </Form.Item>
        <Form.Item className="form-control-item" name="deptId" label="组织机构" >
          <Input disabled />
        </Form.Item>


        <Form.Item {...tailLayout}>
          <Button type="primary" htmlType="submit">提交</Button>
        </Form.Item>
      </Form></div>
  )
}

export default QrcodeList